import { conditionVerifyMap } from './useConditionFormat.js';
import { uniq } from 'lodash-es';
import dayjs from 'dayjs';
function formatResult (list, dataSource, type) {
    let orignData = dataSource.map(item => item);
    let resultData = type === 'OR' ? [] :orignData;
    list.forEach(childItem => {
        const { nodeColumnType, conditionType, nodeColumnName, value, customDateTypeInfo } = childItem.expression || {};
        let finalNodeColumnType = nodeColumnType;
        // 兼容外部数据源数据类型
        switch (nodeColumnType) {
            case 'STRING':
                finalNodeColumnType = 'TEXT';
                break;
            case 'DATE':
                finalNodeColumnType = 'TIMESTAMP';
                break;
            case 'NUMBER':
                finalNodeColumnType = 'DECIMAL';
                break;
        }
        const verifyFn = conditionVerifyMap[`${finalNodeColumnType}|${conditionType}`];
        if (verifyFn) {
            const dataList = orignData.map(item => item[nodeColumnName])
            let result = [];
            if (finalNodeColumnType === 'TIMESTAMP' && ['TOP_N', 'LITTLE_N'].includes(conditionType)) {
                const tempDate = `TEMP__COMPUTED__${nodeColumnName}`
                result = orignData.map(item => {
                    item[tempDate] = item[nodeColumnName] ? new Date(item[nodeColumnName]).getTime() : 0;
                    return item;
                });
                if(conditionType === 'TOP_N') {
                    result = result.sort((a,b)=>b[tempDate]-a[tempDate]).splice(0, value);
                } else {
                    result = result.sort((a,b)=>a[tempDate]-b[tempDate]).splice(0, value);
                }
                if (type === 'OR') {
                    resultData.push(...result);
                }else {
                    orignData = result;
                    resultData = result;
                }
            } else {
                let _tempAndData = [];
                orignData.forEach((dataItem) => {
                    let _result = []
                    let transValue = dataItem[nodeColumnName];
                    if (finalNodeColumnType === 'TIMESTAMP' && transValue) {
                        const dataStr = dataItem[nodeColumnName].replace('年', '-').replace('月', '').replace('日', '').replace('时', ' :').replace('分', ':').replace('秒', '')
                        transValue = dayjs(dataStr).isValid() ? dayjs(dataStr).format(customDateTypeInfo.dateFormat) : dataStr;
                    }
                    _result = verifyFn(transValue, value, value);
                    if (_result) {
                        if (type === 'OR') {
                            resultData.push(dataItem);
                        } else {
                            _tempAndData.push(dataItem);
                        }
                    }
                })
                if (type === 'AND') {
                    orignData = _tempAndData;
                    resultData = _tempAndData;
                }
            }

        }
    })
    return uniq(resultData);
}

/**
 * 这里就是自定义结果过滤，接受两个参数，一个是整个数组，一个是结果过滤的完整格式，上面有示例，
 * 正式使用中，将对应的值替换掉就行
 * @returns
 */
export const filterDataResult = (dataSource, filterConditions) => {
    const firstLevel = filterConditions[0].conditionType;
    let resultAndDataSource = dataSource.map(item => item);
    const resultOrDataSource = []
    filterConditions[0].children.forEach(item => {
        const childCondition = item.conditionType;
        if (!item.children) {
            item.children = [item];
        }
        if (childCondition === 'OR') {
            let tempResult = [];
            tempResult = formatResult(item.children, resultAndDataSource, childCondition)
            if (firstLevel === 'AND') {
                resultAndDataSource = tempResult;
            } else {
                resultOrDataSource.push(...tempResult)
            }
        } else if (childCondition === 'AND') {
            let tempAndData = resultAndDataSource.map(item => item);
            tempAndData = formatResult(item.children, resultAndDataSource, childCondition)
            if (firstLevel === 'AND') {
                resultAndDataSource = tempAndData;
            } else {
                resultOrDataSource.push(...tempAndData);
            }
        }
    });
    if (firstLevel === 'AND') {
        return uniq(resultAndDataSource)
    }
    return uniq(resultOrDataSource)
};

/**
 * 替换key，重命名维度or度量的时候用
 * @param {*} obj1
 * @param {*} obj2
 * @returns
 *
 *  示例
 *   const obj1 = { name: 'name1', sex: 'testSex' };
 *   const obj2 = { name: '张三', sex: '李四', address: 'asdfa' };
 *   const result = replaceKeysWithValues(obj1, obj2);
 *   console.log(result); // 输出: { name1: '张三', testSex: '李四', address: 'asdfa' }
 */
export function replaceKeysWithValues(obj1, obj2) {
    const result = {};
    for (const key in obj2) {
        if (obj1.hasOwnProperty(key)) {
            // 如果 key 在 obj1 中存在，使用 obj1 中对应的 value 作为新 key
            result[obj1[key]] = obj2[key];
        } else {
            // 如果 key 不在 obj1 中，直接使用 obj2 中的 key
            result[key] = obj2[key];
        }
    }
    return result;
}
